package middle;

public class Solution_200 {

    private int count;

    public int numIslands(char[][] grid) {
        count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    dps(grid, i, j);
                }
            }
        }
        return count;
    }

    private void dps(char[][] grid, int row, int col) {
        if (row < 0 || col < 0 || row == grid.length || col == grid[0].length) {
            return;
        }
        if (grid[row][col] == '1') {
            grid[row][col] = '0';
            dps(grid, row, col + 1);
            dps(grid, row, col - 1);
            dps(grid, row + 1, col);
            dps(grid, row - 1, col);
        } else {
            return;
        }
    }

    public static void main(String[] args) {
        Solution_200 model = new Solution_200();
        System.out.println(model.numIslands(new char[][]{
            {'1', '1', '1', '1', '0'},
            {'1', '1', '0', '1', '0'},
            {'1', '1', '0', '0', '0'},
            {'0', '0', '0', '0', '0'}
        }));

        System.out.println(model.numIslands(new char[][]{
            {'1','1','0','0','0'},
            {'1','1','0','0','0'},
            {'0','0','1','0','0'},
            {'0','0','0','1','1'}
        }));
    }
}
